package com.infoland.afanmall.model.guiGe.dialog;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.dialog.BaseNiceDialogFragment;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.guiGe.adapter.GuiGeAdapter1;
import com.infoland.afanmall.model.guiGe.entity.GuiGeEntity;
import com.infoland.afanmall.model.guiGe.entity.OpenGoodEntity;
import com.infoland.afanmall.model.guiGe.entity.ResponsePriceEntity;
import com.infoland.afanmall.model.guiGe.entity.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/****添加购物车商品*/
public class GuiGeDialogFragment extends BaseNiceDialogFragment {
    private ImageView cart_image;//
    private AppCompatTextView cart_price1;//
    private AppCompatTextView cart_price2;//
    private AppCompatTextView cart_kucun;//
    private RecyclerView cart_recl;//
    private AppCompatEditText cart_edtxt;//
    private AppCompatTextView cart_guige;//
    private String now_open_type;    //当前购物状态（立即购买，添加购物车）
    private Object now_good_id;    //当前商品id
    private int now_count;    //当前选中数量
    private OpenGoodEntity openGoodEntity = null;
    private ResponsePriceEntity priceEntity = null;
    public static List<CheckBox> listCheckAll; //装载所有复选框
    public static List<GuiGeEntity.GoodsSpecValListBean> listDataAll; //装在所有实体对象
    private OpenGoodEntity.GoodsPriceBean getGoods_price = null;
    GuiGeAdapter1 guiGeAdapter1;

    @Override
    public int intLayoutId() {
        return R.layout.open_insert_cart;
    }

    //入口
    private void initData() {
        listCheckAll = new ArrayList<>();
        listDataAll = new ArrayList<>();
        //输入框点击事件
        cart_edtxt.setOnFocusChangeListener((v, hasFocus) -> {
            if (openGoodEntity != null) {
                if (now_count <= 0 || now_count > openGoodEntity.getGoodsPrice().getGoods_count()) {
                    ToolsKit.setText(cart_edtxt, openGoodEntity.getGoodsPrice().getGoods_count());
                } else {
                }
            } else {
                ToolsKit.setText(cart_edtxt, 1);
            }
//            if (hasFocus) {
//                // 此处为得到焦点时的处理内容
//            } else {
//                // 此处为失去焦点时的处理内容
//
//            }
        });
        getGoodInfo();
    }

    //根据商品id查询商品信息（初始化页面数据）
    public void getGoodInfo() {
        JSONObject para = new JSONObject();
        para.put("id", now_good_id);
        new OkHttpKit().send(
                response200 -> {
                    openGoodEntity = JSONObject.parseObject(response200, OpenGoodEntity.class);
                    LogKit.E("openGoodEntity   ", "  " + openGoodEntity.getId());
                    initUI(openGoodEntity, openGoodEntity.getAdverGoodsImgs().get(0).getF_url());
                },
                error401 -> {
                    LogKit.E("success401 ---->   ", "  " + error401);
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                },
                errorInternet -> {

                }
        ).post(CONST.GOOD_INFO, para, GuiGeDialogFragment.this);
    }

    // 初始化界面
    private void initUI(OpenGoodEntity openGoodEntity, String f_url) {
        getGoods_price = openGoodEntity.getGoodsPrice();

        ToolsKit.setText(cart_price1, "￥", getGoods_price.getGoods_price());//现价
        ToolsKit.setText(cart_price2, "￥", getGoods_price.getGoods_origin_price());//原价
        ToolsKit.setTextDelete(cart_price2);//
        ToolsKit.setText(cart_kucun, getGoods_price.getGoods_count());//库存
        ToolsKit.setText(cart_guige, getGoods_price.getSpec_name());//规格名
        ToolsKit.setImgFragment(GuiGeDialogFragment.this,f_url, cart_image);//图片
        getGuiGeData();
    }

    //获取规格数据
    private void getGuiGeData() {
        JSONObject para = new JSONObject();
        para.put("id", now_good_id);
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("获取规格数据 ---->   ", "  " + response200);
                    List<GuiGeEntity> guiGeEntities = JSONArray.parseArray(response200, GuiGeEntity.class);
                    if (guiGeEntities.size() > 0) {
                        setGuiGeAdapter(guiGeEntities);
                    } else {
                        this.dismiss();
                    }
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                }
        ).post(CONST.CART_SPREC, para, GuiGeDialogFragment.this);

    }

    //设置规格数据
    private void setGuiGeAdapter(List<GuiGeEntity> guiGeEntities) {
        if (getGoods_price != null) {
            LogKit.E("GuiGeAdapterFragment ---->   ", "  GuiGeAdapterFragment");
            guiGeAdapter1 = new GuiGeAdapter1(R.layout.cart_item, guiGeEntities, getGoods_price.getSpec());
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(getGoods_price.getSpec());
            getGuiGePrice(stringBuilder, guiGeEntities.get(0).getS_goods_id());
            guiGeAdapter1.setGuiGeLinster((item1, position) -> {
                        StringBuilder id_para = new StringBuilder();
                        for (int i = 0; i < listCheckAll.size(); i++) {
//                        LogKit.E("选中状态  ", "  " + listCheckAll.get(i).isChecked() + "   " +
//                                listDataAll.get(i).getSpec_name() + "  -  " + listDataAll.get(i).getS_value());
                            if (listCheckAll.get(i).isChecked()) {
                                int id = listDataAll.get(i).getId();
                                id_para.append(id);
                                id_para.append("-");
                            }
                        }
                        id_para.deleteCharAt(id_para.lastIndexOf("-"));
                        getGuiGePrice(id_para, item1.getGoods_id());
                    }
            );
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            cart_recl.setLayoutManager(layoutManager);
            cart_recl.setAdapter(guiGeAdapter1);

        }
    }

    //根据所选规格，返回价格信息
    private void getGuiGePrice(StringBuilder id_para, int id) {
        JSONObject para = new JSONObject();
        para.put("id", id);
        para.put("goodsSpecJson", id_para.toString());
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("返回价格信息 ---->   ", "  " + response200);
                    updateUi(JSONObject.parseObject(response200, ResponsePriceEntity.class));
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                }
        ).post(CONST.GUI_GE_PRICE, para, getActivity());
    }

    //根据返回价格信息，刷新界面
    @SuppressLint("SetTextI18n")
    private void updateUi(ResponsePriceEntity responseEntity) {
        OpenGoodEntity.GoodsPriceBean goodsPriceBean = JSONObject.parseObject(JSONObject.toJSONString(responseEntity), OpenGoodEntity.GoodsPriceBean.class);
        openGoodEntity.setGoodsPrice(goodsPriceBean);
        LogKit.E("openGoodEntity.getGoodsPrice() ---->   ",
                "  " + JSONObject.toJSONString(openGoodEntity.getGoodsPrice()));
        ToolsKit.setText(cart_price1, "￥", responseEntity.getGoods_price());//现价
        ToolsKit.setText(cart_price2, "￥", responseEntity.getGoods_origin_price());//原价
        ToolsKit.setTextDelete(cart_price2);//
        ToolsKit.setText(cart_kucun, responseEntity.getGoods_count());//库存
        ToolsKit.setText(cart_guige, responseEntity.getSpec_name());//规格名
    }

    //单纯返回规格参数规格
    private void returnGuiGe() {
        /*** 立即购买，所需要的参数**/
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("now_name", now_name);
//        jsonObject1.put("now_price", now_price);
//        jsonObject1.put("now_origin_price", now_origin_price);
//        jsonObject1.put("now_gui_ge", now_gui_ge);
//        jsonObject1.put("now_price_id", now_price_id);
//        jsonObject1.put("now_gui_ge_name", now_gui_ge_name);
//        jsonObject1.put("now_good_id", now_good_id + "");
//        jsonObject1.put("now_count", now_count);
//        jsonObject1.put("now_count_max", now_count_max);
//        jsonObject1.put("now_count_min", now_count_min);
//        jsonObject1.put("now_img_url", now_img_url);
//        jsonObject1.put("now_type", CONST.ORDER_TYPE_NOW_BY);
//        /***添加购物车需要的数据 **/
//        jsonObject1.put("goodsPriceId", priceEntity.getId());
//        jsonObject1.put("goodsCount", now_count);
////
//        jsonObject1.put("id", now_good_id);
//        if (guGeResponseLinster != null) {
//            guGeResponseLinster.responseGuiGe(jsonObject1);
//        } else {
//
//        }
    }

    //直接下单，返回规格参数规格
    private void downOrder() {
        LogKit.E("前往支付。。。。   ", " 前往支付。。。。 ");
//        Bundle bundle = new Bundle();
//        bundle.putString("now_name", now_name);
//        bundle.putDouble("now_price", now_price);
//        bundle.putDouble("now_origin_price", now_origin_price);
//        bundle.putString("now_gui_ge", now_gui_ge);
//        bundle.putInt("now_price_id", now_price_id);
//        bundle.putString("now_gui_ge_name", now_gui_ge_name);
//        bundle.putString("now_good_id", now_good_id + "");
//        bundle.putInt("now_count", now_count);
//        bundle.putInt("now_count_max", now_count_max);
//        bundle.putInt("now_count_min", now_count_min);
//        bundle.putString("now_img_url", now_img_url);
//        bundle.putString("now_type", CONST.ORDER_TYPE_NOW_BY);
//        ToolsKit.go(OrderDownActivity.class, bundle);
    }

    //添加购物车，返回规格参数规格
    private void insertCart() {
        if (priceEntity != null) {
            JSONObject para = new JSONObject();
            para.put("goodsPriceId", priceEntity.getId());
            para.put("goodsCount", now_count);
            if (priceEntity.getGoods_count() >= now_count) {
                new OkHttpKit().send(
                        response200 -> {
                            JSONObject jsonObject = JSONObject.parseObject(response200);
                            if (jsonObject.getBoolean("success")) {
                                ToastUtils.showShort("添加购物车完成");
                            } else {
                                ToastUtils.showShort("添加购物车失败");
                            }
                        },
                        error401 -> {
                            ToastUtils.showShort("登陆后使用");
                        },
                        error -> {
                            ToastUtils.showShort("登录失效，请重新登录");
                        }
                ).post(CONST.CART_INSERT + UserKit.getAccessToken(), para, getActivity());
            } else {
                ToastUtils.showShort("库存不足");
            }
        } else {
        }
    }

    //初始化控件
    @SuppressLint("ResourceAsColor")
    private void initWidget(ViewHolder view) {
        cart_image = view.getView(R.id.cart_image);
        cart_price1 = view.getView(R.id.cart_price1);
        cart_price2 = view.getView(R.id.cart_price2);
        cart_kucun = view.getView(R.id.cart_kucun);
        cart_recl = view.getView(R.id.cart_recl);
        cart_edtxt = view.getView(R.id.cart_edtxt);
        cart_guige = view.getView(R.id.cart_guige);
    }

    @OnClick({R.id.cart_jian, R.id.cart_jia, R.id.cart_bt_ok, R.id.cart_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //销毁
            case R.id.cart_close:
                this.dismiss();
                break;
            /*** 减少商品数量 **/
            case R.id.cart_jian:
                now_count = Integer.valueOf(cart_edtxt.getText().toString());
                if (now_count > 1) {
                    now_count -= 1;
                    ToolsKit.setText(cart_edtxt, now_count);
                }
                break;
            /*** 添加商品数量 **/
            case R.id.cart_jia:
                now_count = Integer.valueOf(cart_edtxt.getText().toString());
                if (now_count < openGoodEntity.getGoodsPrice().getGoods_count()) {
                    now_count += 1;
                    ToolsKit.setText(cart_edtxt, now_count);
                }
                break;
            /***点击确定*/
            case R.id.cart_bt_ok:
                String s = cart_edtxt.getText().toString();
                if (s == null || "".equals(s)) {
                    this.dismiss();
                } else {
                    if (CONST.OPEN_NOW_BY.equals(now_open_type)) {
                        downOrder();
                    } else if (CONST.OPEN_SELECT_GUI_GE.equals(now_open_type)) {
                        returnGuiGe();
                    } else if (CONST.OPEN_INSERT_CART.equals(now_open_type)) {
                        insertCart();
                    }
                    this.dismiss();
                }
                break;
        }
    }

    //初始内调函数
    @Override
    public void convertView(ViewHolder holder, BaseNiceDialogFragment dialog) {
        initWidget(holder);//初始化控件
        initData();
    }

    //初始化
    public GuiGeDialogFragment() {

    }

    //初始化
    public static GuiGeDialogFragment init(Object now_good_id, String now_open_type) {
        return new GuiGeDialogFragment(now_good_id, now_open_type);
    }

    //初始化
    public static GuiGeDialogFragment init(Object now_good_id, String now_open_type, GuGeResponseLinster guiGeDestroy) {
        return new GuiGeDialogFragment(now_good_id, now_open_type, guiGeDestroy);
    }

    //初始化
    @SuppressLint("ValidFragment")
    public GuiGeDialogFragment(Object now_good_id, String now_open_type) {
        this.now_good_id = now_good_id;
        this.now_open_type = now_open_type;
    }

    //初始化
    @SuppressLint("ValidFragment")
    public GuiGeDialogFragment(Object now_good_id, String now_open_type, GuGeResponseLinster linster) {
        this.now_good_id = now_good_id;
        this.now_open_type = now_open_type;
        this.guGeResponseLinster = linster;
    }

    //回调监听
    public interface GuGeResponseLinster {
        void responseGuiGe(JSONObject responseGuiGe);
    }

    //回调监听
    GuGeResponseLinster guGeResponseLinster;

    //回调监听
    public void setGuGeResponseLinster(GuGeResponseLinster guGeResponseLinster) {
        this.guGeResponseLinster = guGeResponseLinster;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    //销毁
    @Override
    public void onDestroy() {
        super.onDestroy();
        listCheckAll = null;
        listDataAll = null;
        ToolsKit.deleteOKHttp(GuiGeDialogFragment.this);
    }


}
